package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v8"
	"leading/global"
	"leading/models"
	"leading/models/res"
	"leading/utils"
	"strconv"
)

// 路由白名单

func AuthMiddle() gin.HandlerFunc {
	return func(c *gin.Context) {
		var url = c.Request.URL.Path
		fmt.Println(url)
		if url == "/api/login" || url == "/api/register" {
			c.Next()
		} else {
			token := c.GetHeader("Authorization")

			if token == "" {
				res.FailWithoutData("无效token", c)
				c.Abort()
				return
			}
			chaims, err := utils.VerifyToken(token)
			if err != nil {
				res.FailWithoutData("token无效", c)
				c.Abort()
				return
			}
			var user models.UserModel
			user = chaims.User
			// 判断用户是否存在
			_, err1 := global.RDB.Get(global.Ctx, "user_"+strconv.Itoa(int(user.ID))).Result()
			if err1 != nil {
				if err1 == redis.Nil {
					res.FailWithoutData("用户不存在", c)
				} else {
					res.FailWithoutData(err1.Error(), c)
				}
				c.Abort()
				return
			}
			c.Set("user", user)
			c.Next()
		}

	}
}
